package udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Receive {
    public static void main(String[] args) throws Exception{
        //1.创建DatagramSocket对象,构造方法中需要指定端口号
        DatagramSocket socket = new DatagramSocket(9999);

        //2.创建一个DatagramPacket
        DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

        //3.接收数据
        socket.receive(packet);


        //4.拆包裹
        byte[] data = packet.getData();
        String s = new String(data,0,packet.getLength());

        //获取数据源ip
        InetAddress address = packet.getAddress();
        String hostAddress = address.getHostAddress();
        System.out.println("获得了从IP：" + hostAddress + "\n发来的数据:" + s);

        //5.释放资源
        socket.close();
    }
}
